package com.gesee.zyspps.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import com.gesee.zys.R;
import com.gesee.zyspps.ZSApplication;
import com.gesee.zyspps.adapter.ExistenceProjectAdater;
import com.gesee.zyspps.constans.MethodFactory;
import com.gesee.zyspps.db.CmsDbNum;
import com.gesee.zyspps.utils.ExcelUtils;
import com.gesee.zyspps.utils.IntentUtil;
import com.gesee.zyspps.utils.StringUtil;
import com.gesee.zyspps.utils.ToastUtil;
import com.gesee.zyspps.widgets.MaterialDialog;
import com.gesee.zyspps.widgets.MyListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.AdapterView.OnItemClickListener;

public class LoginActivity extends BaseActivity
{

    private AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    private Button login, daochu;
    private EditText phone;
    private File file;
    private ExistenceProjectAdater adapter;
    private ArrayList<ArrayList<String>> pointList;
    private ArrayList<ArrayList<String>> lineList;
    private String[] pointsTitle =
        { "物探点号", "井底埋深", "管线类型", "附属物", "特征","管点编号小标", "井盖规格", "井盖材质", "井盖尺寸", "井筒深度", "井室尺寸", "淤堵情况", "管偏井编号", "道路名称", "权属单位", "建设年代", "符号旋转角度", "图幅号", "探测单位", "探测日期", "工程名称", "测区名称", "街道名称", "小区名称", "社区名称",
                " 探测人员", "X坐标", "y坐标", "备注","井室类型","探测时水深","探查时泥深","检查井等级","检查井照片编号" };

    private String[] linesTitle =
    { "管线长度", "起始物探点号", "终止物探点号", "起始埋深", "终止埋深", "管线类型", "埋设方式", "材质", "管径或断面尺寸", "套管或管沟尺寸", "压力", "电压", "流向", "电缆条数", "总孔数", "已用孔数", "权属单位名称", "建设年代", "道路名称", "起点管偏", "终点管偏", "所属街道", "所属社区",
            "所属小区", "测区名称", "探测单位", "探测日期", "工程名称", "探测人员", "备注" ,"电缆条数" ,"已用孔数","总孔数" ,"录像编号1","录像编号2"};

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        pointList = new ArrayList<ArrayList<String>>();
        lineList = new ArrayList<ArrayList<String>>();
        login = (Button) findViewById(R.id.login);
        daochu = (Button) findViewById(R.id.daochu);
        
        //daochu.setVisibility(View.GONE);
        
        phone = (EditText) findViewById(R.id.phone);
        if (ZSApplication.getInstance().getConfig("phone").equals("null"))
        {
            phone.setText("");
        }
        else
        {
            phone.setText(ZSApplication.getInstance().getConfig("phone"));
        }
        daochu.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                String dbName = ZSApplication.getInstance().getConfig("newDBName");
                if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
                {
                    ToastUtil.show(context, "SDCard不存在~");
                    return;
                }
                exportProject();
                /*if (dbName != null && (!dbName.equals("")))
                {
                    initLines(dbName);
                    initPoints(dbName);
                }
                else
                {
                    ToastUtil.show(LoginActivity.this, "没有打开任何项目!");
                }*/
            }
        });
        login.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub

                if (!StringUtil.isEmpty(phone.getText().toString().trim()))
                {
                    asyncHttpClient.get("http://cz900126.6655.la:13526/PipeCollectService/ReqHandler", MethodFactory.login(phone.getText().toString().trim()), new AsyncHttpResponseHandler()
                    {

                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
                        {
                            // TODO Auto-generated method stub
                            String data = new String(responseBody);
                            if ((data.trim()).equals("failure"))
                            {
                                ToastUtil.show(LoginActivity.this, "您的手机号和deviceid存在错误，请联系管理员！");
                            }
                            else if ((data.trim()).equals("success"))
                            {
                                if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
                                {
                                    ToastUtil.show(context, "SDCard不存在~");
                                    return;
                                }
                                IntentUtil.startActivity(MainActivity.class);
                                ZSApplication.getInstance().setConfig("phone", phone.getText().toString().trim());
                            }

                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
                        {
                            // TODO Auto-generated method stub
                            ToastUtil.show(LoginActivity.this, "连接超时");
                        }
                    });
                }
                else
                {
                    //IntentUtil.startActivity(MainActivity.class);
                    ToastUtil.show(LoginActivity.this, "电话号码必须填写!");
                }

            }
        });
    }
    
    private void exportProject()
    {
        final List<CmsDbNum> dbList = ZSApplication.getDaoSession("zyspps-db").getCmsDbNumDao().loadAll();

        View openProjectView = LayoutInflater.from(context).inflate(R.layout.open_project_dialog, null);
        final MyListView listView = (MyListView) openProjectView.findViewById(R.id.listView);

        adapter = new ExistenceProjectAdater(context);
        adapter.setList(dbList);
        listView.setAdapter(adapter);

        final MaterialDialog dialog = new MaterialDialog(context, "可以导出的项目名", openProjectView);
        dialog.show();
        dialog.getButtonAccept().setVisibility(View.GONE);
        dialog.getButtonCancel().setVisibility(View.GONE);

        listView.setOnItemClickListener(new OnItemClickListener()
        {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                // TODO Auto-generated method stub
                String daName = dbList.get(position).getDbName();
                initPoints(daName);
                initLines(daName);
                dialog.dismiss();
            }
        });
    }

    public String getSDPath()
    {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if (sdCardExist)
        {
            sdDir = Environment.getExternalStorageDirectory();
        }
        String dir = sdDir.toString();
        return dir;

    }

    private ArrayList<ArrayList<String>> getPointData(String dbName, String sql)
    {
        pointList.clear();
        Cursor mCrusor = ZSApplication.getDaoSession(dbName).getCmsPointsDao().getDatabase().rawQuery(sql, null);
        while (mCrusor.moveToNext())
        {
            ArrayList<String> beanList = new ArrayList<String>();
            beanList.add(mCrusor.getString(1));
            beanList.add(mCrusor.getString(2));
            beanList.add(mCrusor.getString(3));
            beanList.add(mCrusor.getString(4));
            beanList.add(mCrusor.getString(5));
            beanList.add(mCrusor.getString(6));
            beanList.add(mCrusor.getString(7));
            beanList.add(mCrusor.getString(8));
            beanList.add(mCrusor.getString(9));
            beanList.add(mCrusor.getString(10));
            beanList.add(mCrusor.getString(11));
            beanList.add(mCrusor.getString(12));
            beanList.add(mCrusor.getString(13));
            beanList.add(mCrusor.getString(14));
            beanList.add(mCrusor.getString(15));
            beanList.add(mCrusor.getString(16));
            beanList.add(mCrusor.getString(17));
            beanList.add(mCrusor.getString(18));
            beanList.add(mCrusor.getString(19));
            beanList.add(mCrusor.getString(20));
            beanList.add(mCrusor.getString(21));
            beanList.add(mCrusor.getString(22));
            beanList.add(mCrusor.getString(23));
            beanList.add(mCrusor.getString(24));
            beanList.add(mCrusor.getString(25));
            beanList.add(mCrusor.getString(26));
            beanList.add(mCrusor.getString(27));
            beanList.add(mCrusor.getString(28));
            beanList.add(mCrusor.getString(29));
            beanList.add(mCrusor.getString(30));
            beanList.add(mCrusor.getString(31));
            beanList.add(mCrusor.getString(32));
            beanList.add(mCrusor.getString(33));
            beanList.add(mCrusor.getString(34));
            pointList.add(beanList);
        }
        mCrusor.close();
        return pointList;
    }

    private ArrayList<ArrayList<String>> getLinesData(String dbName, String sql)
    {
        lineList.clear();
        Cursor mCrusor = ZSApplication.getDaoSession(dbName).getCmsLineDao().getDatabase().rawQuery(sql, null);
        while (mCrusor.moveToNext())
        {
            ArrayList<String> beanList = new ArrayList<String>();
            beanList.add(mCrusor.getString(1));
            beanList.add(mCrusor.getString(2));
            beanList.add(mCrusor.getString(3));
            beanList.add(mCrusor.getString(4));
            beanList.add(mCrusor.getString(5));
            beanList.add(mCrusor.getString(6));
            beanList.add(mCrusor.getString(7));
            beanList.add(mCrusor.getString(8));
            beanList.add(mCrusor.getString(9));
            beanList.add(mCrusor.getString(10));
            beanList.add(mCrusor.getString(11));
            beanList.add(mCrusor.getString(12));
            beanList.add(mCrusor.getString(13));
            beanList.add(mCrusor.getString(14));
            beanList.add(mCrusor.getString(15));
            beanList.add(mCrusor.getString(16));
            beanList.add(mCrusor.getString(17));
            beanList.add(mCrusor.getString(18));
            beanList.add(mCrusor.getString(19));
            beanList.add(mCrusor.getString(20));
            beanList.add(mCrusor.getString(21));
            beanList.add(mCrusor.getString(22));
            beanList.add(mCrusor.getString(23));
            beanList.add(mCrusor.getString(24));
            beanList.add(mCrusor.getString(25));
            beanList.add(mCrusor.getString(26));
            beanList.add(mCrusor.getString(27));
            beanList.add(mCrusor.getString(28));
            beanList.add(mCrusor.getString(29));
            beanList.add(mCrusor.getString(30));
            beanList.add(mCrusor.getString(31));
            beanList.add(mCrusor.getString(32));
            beanList.add(mCrusor.getString(33));
            beanList.add(mCrusor.getString(34));
            beanList.add(mCrusor.getString(35));
            lineList.add(beanList);
        }
        mCrusor.close();
        return lineList;
    }

    public static void makeDir(File dir)
    {
        if (!dir.getParentFile().exists())
        {
            makeDir(dir.getParentFile());
        }
        dir.mkdir();
    }

    /*@SuppressLint("SimpleDateFormat")
    public void initPoints(String dbName)
    {
        String sql = "select * from " + "CMS_POINTS";
        file = new File(getSDPath() + "/Zyspps");
        makeDir(file);
        
         * File file1 = new File(file.toString() + "/" + dbName + "(管点)" +
         * ".xls"); if (file1.isFile() && file1.exists()) { file1.delete(); }
         
        ExcelUtils.initExcel(file.toString() + "/" + dbName + "(管点)" + ".xls", pointsTitle);
        ExcelUtils.writeObjListToExcel(getPointData(dbName, sql), getSDPath() + "/Zyspps" + "/" + dbName + "(管点)" + ".xls", this);
    }

    public void initLines(String dbName)
    {
        String sql = "select * from " + "CMS_LINE";
        file = new File(getSDPath() + "/Zyspps");
        makeDir(file);
        
         * File file1 = new File(file.toString() + "/" + dbName + "(管线)" +
         * ".xls"); if (file1.isFile() && file1.exists()) { file1.delete(); }
         
        ExcelUtils.initExcel(file.toString() + "/" + dbName + "(管线)" + ".xls", linesTitle);
        ExcelUtils.writeObjListToExcel(getLinesData(dbName, sql), getSDPath() + "/Zyspps" + "/" + dbName + "(管线)" + ".xls", this);
    }*/
    
    /**
     * 
     * @Title: initData
     * @Description: TODO(导出数据)
     * @author fujianxiong
     * @throws
     */
    @SuppressLint("SimpleDateFormat")
    public void initPoints(String dbName)
    {
        String sql = "select * from " + "CMS_POINTS";
        file = new File(getSDPath() + "/Zyspps");
        makeDir(file);
        /*
         * File file1 = new File(file.toString() + "/" + dbName + "(管点)" +
         * ".xls"); if (file1.isFile() && file1.exists()) { file1.delete(); }
         */
        ExcelUtils.initExcel(file.toString() + "/" + dbName + "_管点" + ".xls", pointsTitle);
        ExcelUtils.writeObjListToExcel(getPointData(dbName, sql), getSDPath() + "/Zyspps" + "/" + dbName + "_管点" + ".xls", this);
    }

    public void initLines(String dbName)
    {
        String sql = "select * from " + "CMS_LINE";
        file = new File(getSDPath() + "/Zyspps");
        makeDir(file);
        /*
         * File file1 = new File(file.toString() + "/" + dbName + "(管线)" +
         * ".xls"); if (file1.isFile() && file1.exists()) { file1.delete(); }
         */
        ExcelUtils.initExcel(file.toString() + "/" + dbName + "_管线" + ".xls", linesTitle);
        ExcelUtils.writeObjListToExcel(getLinesData(dbName, sql), getSDPath() + "/Zyspps" + "/" + dbName + "_管线" + ".xls", this);
    }
}
